<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <link href="/static/resource/album/css/reset.css" rel="stylesheet"/>
    <link href="/static/resource/album/css/model.css" rel="stylesheet"/>
    <script src="/static/resource/album/js/jquery.min.js"></script>
    <script src="/static/resource/album/js/rem.min.js"></script>
    <link href="/static/resource/album/css/cropper.min.css" rel="stylesheet">
    <script src="/static/resource/album/js/cropper.min.js"></script>
    <title>亲子莜面体验营</title>
    <style>
        #picframe {
            position: absolute;
            cursor: move;
        }

        #mask {
            position: absolute;
            cursor: move;
            z-index: 1;
        }
        .photo-box{
            background: url('background.jpg');
        }
    </style>
</head>
<body>
<div class="mask">
    <div class="photo-box">
        <div class="container" style="max-height: 6.99rem;">
            <img src="{$img_url}" width="800" height="800">
        </div>
        <img src="{$album_img_url}" id="picframe" />
        <div id="mask"></div>
    </div>
    <!--<div class="pic"></div>-->
    <div class="btn-group">
        <input type="text" value="{$id}" style="display: none;" id="huodong">
        <input type="button" value="重选照片" class="btn-again" id = "select"/>
        <div class="btn-sure" onclick="getData();">确定</div>
    </div>
</div>

<script>
    var is_move = false;
    var move_x = 0;
    var move_y = 0;
    var frame_height = 681;
    var frame_width = 710;
    //重新选择
    $('#select').click(function(){
        var id = $('#huodong').val()
        location.href='imgchoice?id='+id;
    })

    function back() {
        location.href = "{:url('index')}";
    }
    function getData() {
        var roundedCanvas = getRoundedCanvas($('.container > img').cropper("getCroppedCanvas"));
        var dataUrl = roundedCanvas.toDataURL();
        $("#result").attr('src', dataUrl);
        doUpload('crop_img', dataURLtoFile(dataUrl, 'crop_img.png'));
    }

    function getRoundedCanvas(sourceCanvas) {

        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        var width = sourceCanvas.width;
        var height = sourceCanvas.height;
        var offsetHeight = Math.floor(height * 0.1);
        var offsetWidth = Math.floor(width * 0.08);

        canvas.width = width;
        canvas.height = height;
        context.beginPath();
        context.rect(0, 0, width, height);
        context.strokeStyle = 'rgba(0,0,0,0)';
        context.stroke();
        context.clip();
        context.drawImage(sourceCanvas, offsetWidth, offsetHeight, width - offsetWidth * 2, height - offsetHeight * 2);
        context.drawImage(document.getElementById('picframe'), 0, 0, width, height);
        return canvas;
    }

    function doUpload(filename, fileobj) {
        var formData = new FormData();
        formData.append(filename, fileobj);
        $.ajax({
            url: "{:url('cropUpload')}",
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                if (returndata.status) {
                    location.href = "{:url('imgshow')}";
                } else {
                    alert(returndata.msg);
                }
            },
            error: function () {
                alert("文件上传异常!");
            }
        });
    }

    /**
     * 将以base64的图片url数据转换为Blob文件格式
     * @param urlData 用url方式表示的base64图片
     */
    function convertBase64UrlToBlob(urlData) {
        var bytes = window.atob(urlData.split(',')[1]); //去掉url的头，并转换为byte
        //处理异常,将ascii码小于0的转换为大于0
        var ab = new ArrayBuffer(bytes.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }
        return new Blob([ab], {
            type: 'image/png'
        });
    }

    function dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(',');
        var mime = arr[0].match(/:(.*?);/)[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        //转换成file对象
        return new File([u8arr], filename, {type: mime});
        //转换成成blob对象
        //return new Blob([u8arr],{type:mime});
    }

    //可以使用$.fn.cropper方法来初始化该图片剪裁插件。
    $('.container > img').cropper({
        checkImageOrigin: false,
        background: false,
        guides: false,
        dragCrop: false,
        movable: false,
        aspectRatio: frame_width / frame_height,
        built: function () {
            //console.log($(this).cropper('getCropBoxData'))
            var cropObj = $(this).cropper('getCropBoxData');
            var offset = cropObj.width * 0.1;

            $('#picframe,#mask').css({
                "left": cropObj.left - offset,
                "top": cropObj.top - offset,
                "height": cropObj.height * 1.15,
                "width": cropObj.width * 1.15
            });
        }
    });

    $('#mask').mousedown(function (e) {
        is_move = true;
        move_x = e.pageX;
        move_y = e.pageY;
        //$('.container > img').cropper("move",20,0);
    });
    $('#mask').mouseup(function (e) {
        is_move = false;
        //$('.container > img').cropper("move",20,0);
    });
    $('#mask').mouseout(function (e) {
        is_move = false;
    });
    $('#mask').mousemove(function (e) {
        if (is_move) {
            $('.container > img').cropper("move", e.pageX - move_x, e.pageY - move_y);
            move_x = e.pageX;
            move_y = e.pageY;
        }
        //$('.container > img').cropper("move",20,0);
    });
    //    var myElement = document.getElementById('mask');
    //    var mc = new Hammer(myElement);
    //    mc.on("panstart", function(ev) {
    //        //console.log(ev.pointers);
    //        is_move = true;
    //        move_x = e.pageX;
    //        move_y = e.pageY;
    //    });
    function onTouchStart(e) {
        is_move = true;
        move_x = e.touches[0].pageX;
        move_y = e.touches[0].pageY;
    }
    //touchend touchleave touchcancel
    function onTouchEnd(e) {
        is_move = false;
    }
    function onTouchMove(e) {
        if (is_move) {
            $('.container > img').cropper("move", e.touches[0].pageX - move_x, e.touches[0].pageY - move_y);
            move_x = e.touches[0].pageX;
            move_y = e.touches[0].pageY;
        }
    }
    var mask = document.getElementById('mask');
    mask.addEventListener('touchstart', onTouchStart, false);
    mask.addEventListener('touchend', onTouchEnd, false);
    mask.addEventListener('touchleave', onTouchEnd, false);
    mask.addEventListener('touchcancel', onTouchEnd, false);
    mask.addEventListener('touchmove', onTouchMove, false);
    //
    //    $result = $('#result');
    //    $image = $('.container > img');
    //    croppedCanvas = $image.cropper('getCroppedCanvas');
    //    console.log(croppedCanvas);
    // Round
    //roundedCanvas = getRoundedCanvas(croppedCanvas);
    //$result.attr('src',roundedCanvas.toDataURL());
</script>
</body>
</html>